class lazyTarget{
    constructor(el) {
        this.isVisible = false;
        this.first = true;
        this.offset = parseInt(el.dataset.offset)||(100);
        if(window.matchMedia("(orientation: portrait)").matches){
            this.offset = 110;
        }
        let mar = "0px 0px "+(this.offset)+"% 0px";
        let op = {
            root: null,
            rootMargin: mar,
            threshold: [0,0.1,0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
        };
        let src_ = el.dataset.src;
        if(this.shu&&el.dataset.appsrc!==undefined){
            src_ = el.dataset.appsrc;
        }
        if(this.browser_check_webp()&&src_.split('jpg').length>1&&src_.split('webp').length===1){
            src_ = el.dataset.src.replace('.jpg',".jpg.webp")
        }else if(this.browser_check_webp()&&src_.split('png').length>1&&!el.dataset.no&&src_.split('webp').length===1){
            src_ = el.dataset.src.replace('.png',".png.webp")
        }
        this.observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                this.isVisible = entry.intersectionRatio > 0.0;
                if(this.first&&this.isVisible){
                    switch (el.nodeName) {
                        case "VIDEO":
                            if(!this.shu){
                                el.setAttribute("src", src_);
                                el.classList.add('loaded');
                            }
                            break;
                        case "IMG":
                            el.setAttribute("src", src_);
                            el.classList.add('loaded');
                            break;
                        default:
                            el.style.backgroundImage = "url(" + src_ + ")";
                            el.classList.add('loaded');
                            break;
                    }
                    this.first = false;
                }
            });
        },op);
        this.observer.observe(el.parentNode);//对元素监听是否在可视区
    }
    browser_check_webp() {
        try {
            return document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0;
        } catch(err) {
            return false;
        }
    }
}
export class LazyLoading{
    constructor(option) {
        this.images = [];
        this.defaults = {el: '.lazy',call:()=>{}};
        this.options = Object.assign(this.defaults, option || {});
        this.imgEl = document.querySelectorAll(this.options.el);
        const self = this;
        this.imgEl.forEach((item,index)=>{
            new lazyTarget(item);
            if(index===(self.imgEl.length-1)){
                this.options.call();
            }
        });
    }
}